package com.epi.service.Impl;

import com.epi.basic.constant.RedisKey;
import com.epi.basic.model.ResponseVO;
import com.epi.domain.dto.UserLoginReq;
import com.epi.domain.security.LoginUser;
import com.epi.service.LoginService;
import com.epi.utils.JwtUtil;
import com.epi.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author dxy
 * @version 1.0
 */
@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    AuthenticationManager authenticationManager;
    @Autowired
    RedisCache redisCache;


    @Override
    public ResponseVO login(UserLoginReq req) {
        // 1 认证
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(req.getUsername(), req.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("登陆失败");
        }
        // 2 保存会话信息 jwt
        LoginUser user = (LoginUser) authenticate.getPrincipal();
        String userId = user.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);
        String key = RedisKey.USER_AUTHORIZATION + userId;
        redisCache.setCacheObject(key, user);
        return ResponseVO.success(jwt);
    }

    @Override
    public ResponseVO logout() {
        LoginUser loginUser  = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        redisCache.deleteObject(RedisKey.USER_AUTHORIZATION+userId);
        return ResponseVO.success(loginUser);
    }
}
